<!-- 登录码 -->
<template>
  <div class="bgLoar">
    <div class="content">
      <i class="el-icon-circle-close clone_btn changeHanld" @click="handleClick"></i>
      <div class="bg_title">微信登录</div>
      <canvas ref="qrcode">
        <!-- <img src="../../../static/image/userInfo/fenxiangweima.png" alt="" /> -->
      </canvas>
      <div class="bg_text">
        <div class="top">请使用微信扫描二维码登录</div>
        <div class="button">"比目镜网站"</div>
      </div>
    </div>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { get, post } from "../../http/axios.js"; // 发送请求数据接口
import { commonRequest, postRequest } from "../../api/api.js";
import { mapActions, mapMutations } from "vuex";
import QRCode from "qrcode"; // 生成二维码插件
import { sessionDeposit, sessionTake } from "../../util/validate.js";

export default {
  props: {
    isLogin: {
      type: Boolean,
      defalut: false
    }
  },
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      timeId: null,
      signUrl: "/api/getOpenIdByRandomKey",
      randomKey: ""
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    isLogin(val) {
      if (val) {
        this.getQrcode();
      } else {
        clearInterval(this.timeId);
      }
    }
  },
  //方法集合
  methods: {
    ...mapActions(["hanldOpenIdLogin"]),
    ...mapMutations(["setBackName", "setIsShow"]),
    // 扫码轮询
    isSuccessLogin() {
      commonRequest(this.signUrl + "?randomKey=" + this.randomKey).then(res => {
        if (res) {
          //获取到openId
          let data = {
            openId: res
          };
          sessionDeposit("openId", data.openId);
          this.hanldOpenIdLogin(data).then(res => {
            if (!res) {
              let backName = this.$store.state.backName;
              this.$message.success({
                message: backName ? "登录成功,跳转页面" : "登录成功",
                type: "success"
              });
              const time = new Date().getTime() + 24 * 60 * 60 * 1000 * 7;
              localStorage.setItem("endTime", time);
              if (backName) {
                this.setBackName("");
                setTimeout(() => {
                  this.$router.back();
                }, 3000);
              } else {
                this.setIsShow(false);
                this.$emit("jieshou", false);
                this.$router.push("/");
              }
            }
          });
          clearInterval(this.timeId);
        }
      });
    },
    // 生成二维码
    qrcode(url) {
      let _this = this;
      let opts = {
        errorCorrectionLevel: "H",
        type: "image/png", // 生成的二维码类型
        quality: 1, // 二维码质量
        margin: 5, // 二维码留白边距
        width: 200, // 宽度
        color: {
          dark: "#333", // 前景色
          light: "#fff" // 背景色
        }
      };
      QRCode.toCanvas(_this.$refs.qrcode, url, opts);
    },
    // 点击关闭按钮
    handleClick() {
      this.$emit("isShowCode", false);
    },
    // 获取二维码
    getQrcode() {
      var url = "/WeiXin/GetQrCodeTicket";
      this.randomKey = this.randomNum(10000, 99999);
      post("https://old.51bmj.cn" + url, {
        expire_seconds: 300,
        scene_id: this.randomKey
      }).then(res => {
        // console.log(res);
        this.qrcode(res.url);
        this.timeId = setInterval(() => {
          this.isSuccessLogin();
        }, 2000);
      });
    },
    randomNum(minNum, maxNum) {
      switch (arguments.length) {
        case 1:
          return parseInt(Math.random() * minNum + 1, 10);
          break;
        case 2:
          return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
          break;
        default:
          return 0;
          break;
      }
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {}
};
</script>
<style lang="less" scoped>
//@import url(); 引入公共css类
.bgLoar {
  position: fixed;
  width: 100vw;
  height: 100vh;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
  background-color: #333;
  overflow: hidden;

  .clone_btn {
    position: absolute;
    right: 10px;
    top: 10px;
    font-size: 30px;
    color: #fff;
  }

  .content {
    width: 400px;
    height: 400px;
    // border: 1px solid rgb(83, 82, 82);
    position: relative;
    top: 80px;
    left: 50%;
    right: 50%;
    transform: translate(-50%);
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    align-items: center;

    .bg_title {
      font-size: 26px;
      color: #fff;
    }

    .bg_image {
      width: 250px;

      img {
        width: 100%;
      }
    }

    .bg_text {
      height: 70px;
      width: 350px;
      background-color: #232323;
      padding: 10px 20px;
      border-radius: 50px;
      color: #fff;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      font-size: 14px;
    }
  }
}
</style>
